package com.ziq.zcamp.dialog.share

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.Toast
import com.facebook.common.util.UriUtil
import com.facebook.imagepipeline.request.ImageRequest
import com.gmlive.camp.dialog.share.SharePicCacheInterface
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.life.CampLifeInfo
import com.ziq.zcamp.databinding.LayoutSharePicCacheCampLifeBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.StorageUtil
import com.ziq.zcamp.util.io.IOUtils
import java.io.FileOutputStream

class SharePicCacheLayoutCampLife @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), SharePicCacheInterface {

    var binding : LayoutSharePicCacheCampLifeBinding = LayoutSharePicCacheCampLifeBinding.inflate(LayoutInflater.from(context), this, true)

    var imageList = mutableListOf<String>()
    var way = ""

    var campInfo : CampLifeInfo? = null

    @SuppressLint("SetTextI18n")
    fun setCampLifeData(data: CampLifeInfo){
        campInfo = data
        way = "camp_life"

        data.user_image.let {
            if (it == null){
                binding.ivUserImage.setImageResource(R.drawable.icon_default_avatar)
            }else{
                ImageUtil.updateImageFromNetwork(binding.ivUserImage, data.user_image, ImageRequest.CacheChoice.DEFAULT)
            }
        }
        data.user_name.let {
            if (it == null){
                binding.tvUserTitle.text = "${data.user_name}"

            }else{
                binding.tvUserTitle.text = "${data.user_name}的露营人生"
            }
        }
        binding.tvCampTime.text = data.time

        val list = mutableListOf(data.camp_num?:0,data.place_num?:0, data.city_num?:0)
        val max = list.maxOrNull()
        val len = max.toString().length
        val difference = if (len > 3) (len -3 ) * 8 else 0
        binding.tvNumOfCamp.setTextSize(TypedValue.COMPLEX_UNIT_DIP,32.0F - difference)
        binding.tvNumOfPlace.setTextSize(TypedValue.COMPLEX_UNIT_DIP,32.0F - difference)
        binding.tvNumOfCity.setTextSize(TypedValue.COMPLEX_UNIT_DIP,32.0F - difference)

        binding.tvNumOfCamp.text = data.camp_num.toString()
        binding.tvNumOfPlace.text = data.place_num.toString()
        binding.tvNumOfCity.text = data.city_num.toString()

        val uri: Uri = Uri.Builder()
            .scheme(UriUtil.LOCAL_FILE_SCHEME)
            .path(data.map_image)
            .build()
        binding.ivMapImage.setImageURI(uri)

        ImageUtil.updateImageFromNetwork(binding.ivAppletCode, data.mini_image, ImageRequest.CacheChoice.DEFAULT)
    }

    /**
     * 图片加载完成
     */
    override fun checkPictureBitmap(action : ()->Unit){
        val length = imageList.size
        var index = -1
        fun callback(){
            index++
            if(index < length){
                val url = imageList[index]
                ImageUtil.getBitmap(0, url, 0, 0) { _, _ ->
                    callback()
                }
            } else {
                action.invoke()
            }
        }
        callback()
    }

    override fun getMiniProgramPath(): String {
        val suffix = if (campInfo?.other_id == null){ "" } else { "?uid=${campInfo?.other_id}" }
        return "subpages/community/camp-life/index${suffix}"
    }

    /**
     * 完整卡片
     */
    override fun getTotalLayoutBitmap() : Bitmap?{
        return ImageUtil.convertViewToBitmap(binding.root,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_600))
    }

    /**
     * 小程序分享标题
     */
    override fun getTitleForMiniProgram() : String{
        var content = ""
        content = if(campInfo != null ){
            if(campInfo?.user_name?.isNotEmpty() == true){
                "${campInfo?.user_name}的露营人生"
            }else{
                "露营人生"
            }
        }else{
            "露营人生"
        }
        return content
    }
    /**
     * 小程序分享卡片封面
     */
    override fun getCoverBitmapForMiniProgram(action : (bitmap : Bitmap?)->Unit){
        val bitmap = ImageUtil.convertViewToBitmap(binding.clRoot,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_600))
        action.invoke(bitmap)
    }
    /**
     * 复制链接
     */
    override fun getLinkTxt() : String{
        // 露营人生无复制链接
        return ""
    }

    /**
     * 保存到本地
     */
    override fun onSavePicToLocal(source : String,finish:()->Unit){
        checkPictureBitmap {
            savePicToLocal(source,getTotalLayoutBitmap())
            finish()
        }
    }

    private fun savePicToLocal(source : String,bitmap : Bitmap?){
        try {
            if(bitmap != null){
                val path = StorageUtil.getPictureFileWith("camp_share_${way}_${System.currentTimeMillis()}.png")
                var fos: FileOutputStream? = null
                try {
                    fos = FileOutputStream(path)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    fos.flush()
                } catch (e: Exception) {
                } finally {
                    IOUtils.close(fos)
                }
                if (path.exists() && path.length() > 0) {
                    ImageUtil.insertImageToAlbum(context, path.absolutePath)
                    val msg = "保存成功"
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                } else {
                    val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                }
            }
        } catch (ignore: Exception) {
            val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        }
    }
}